package net.haveraid.controller;

import java.util.Map;

import javax.validation.Valid;

import net.haveraid.data.Member;
import net.haveraid.data.Player;
import net.haveraid.data.Raid;
import net.haveraid.data.RaidCalendar;
import net.haveraid.service.RaidService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;

@Controller
@RequestMapping("/raid")
@SessionAttributes("raid")
public class RaidController {
	
	private static final Logger logger = LoggerFactory.getLogger(RaidController.class);

	@Autowired
	private RaidService raidService;

	public Raid getRaid() {
		return new Raid();
	}

	@RequestMapping(method = RequestMethod.GET)
	public String getAll(Map<String, Object> map, Model model) {
		RaidCalendar cal = raidService.getRaidCalendar();

		model.addAttribute("cal", cal);
		return "raid/list";
	}
	
	@RequestMapping(value="/{id}/sign",method=RequestMethod.GET)
	public @ResponseBody String sign(@PathVariable Integer id,@RequestParam(required=true) String type) {
		Raid r = raidService.get(id);
		Player p = new Player();
		p.setName("Steve");
		if("u".equals(type)) {
			logger.info("Signing off");
			raidService.signDownMember(r, p);
			return "true";
		} else if("t".equals(type)) {
			logger.info("Signing tank");
			raidService.signUpMember(r, p, Member.Type.Tank);
			return "true";
		}
		return "false";
	}

	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	public String view(@PathVariable Integer id, Model model) {
		model.addAttribute("r", raidService.get(id));

		return "raid/view";
	}

	@RequestMapping("/new")
	public String newRaid(Model model) {
		model.addAttribute("raid", getRaid());
		return "raid/new";
	}

	@RequestMapping(value = "/create", method = RequestMethod.POST)
	public String create(@ModelAttribute("raid") @Valid Raid raid,
			BindingResult bindignResult, SessionStatus status) {
		if (bindignResult.hasErrors()) {
			return "raid/new";
		}
		raidService.add(raid);
		status.setComplete();
		return "redirect:/raid/" + raid.getId();
	}
}
